import { getCartList, updateCartCount, delCartList } from '@/api/cart'
import { Toast } from 'vant'
export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  mutations: {
    setCartList (state, newList) {
      state.cartList = newList
    },
    toggleCheck (state, goodsId) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.isChecked = !goods.isChecked
    },
    toggleCheckAll (state, flag) {
      state.cartList.forEach(item => {
        item.isChecked = flag
      })
    },
    updateCartCount (state, obj) {
      const goods = state.cartList.find(item => item.goods_id === obj.goodsId)
      goods.goods_num = obj.goodsNum
    }
  },
  actions: {
    async getCartAction (context) {
      const { data } = await getCartList()
      //   后台返回的数据不包含复选框属性，我们需要自己为每个商品添加ischecked属性
      data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCartList', data.list)
    },
    async updateCartCountAction (context, obj) {
      await updateCartCount(obj.goodsId, obj.goodsNum, obj.goodsSkuId)
      // 修改本地数据
      context.commit('updateCartCount', obj)
    },
    async delCartListAction (context) {
      const goods = context.getters.getIscheckedList
      const goodIds = goods.map(item => item.id)
      await delCartList(goodIds)
      setTimeout(() => Toast('删除成功'), 100)

      // 重新拉取最新的购物车数据 (重新渲染)
      context.dispatch('getCartAction')
    }
  },
  getters: {
    // 获取购物车商品总数
    getCartTotal (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },

    // 获取勾选商品列表
    getIscheckedList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    // 获取购物车勾选商品总数
    getCartIscheckedNumTotal (state, getters) {
      return getters.getIscheckedList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 获取勾选商品总价
    getCartIscheckedPriceTotal (state, getters) {
      return getters.getIscheckedList.reduce((sum, item) => sum + item.goods.goods_price_min * item.goods_num, 0).toFixed(2)
    },
    // 是否全选
    getIscheckedAll (state) {
      return state.cartList.every((item) => item.isChecked)
    }
  }
}
